Your First AI application

Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.

In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset from Oxford of 102 flower categories, you can see a few examples below.

The project is broken down into multiple steps:

  • Load the image dataset and create a pipeline.
  • Build and Train an image classifier on this dataset.
  • Use your trained model to perform inference on flower images.

We'll lead you through each part which you'll implement in Python.

When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.

Import Resources

In [4]:
# The new version of dataset is only available in the tfds-nightly package.
%pip --no-cache-dir install tensorflow-datasets --user
#%pip --no-cache-dir install tfds-nightly
%pip --no-cache-dir install tfds-nightly --user 
!pip install tensorflow --upgrade --user
# DON'T MISS TO RESTART THE KERNEL
Requirement already satisfied: tensorflow-datasets in /opt/conda/lib/python3.7/site-packages (1.2.0)
Requirement already satisfied: six in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (1.12.0)
Requirement already satisfied: requests>=2.19.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (2.22.0)
Requirement already satisfied: future in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (0.18.2)
Requirement already satisfied: tensorflow-metadata in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (0.14.0)
Requirement already satisfied: termcolor in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (1.1.0)
Requirement already satisfied: dill in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (0.3.1.1)
Requirement already satisfied: attrs in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (19.3.0)
Requirement already satisfied: numpy in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (1.17.4)
Requirement already satisfied: tqdm in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (4.36.1)
Requirement already satisfied: absl-py in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (0.8.1)
Requirement already satisfied: promise in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (2.2.1)
Requirement already satisfied: wrapt in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (1.11.2)
Requirement already satisfied: psutil in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (5.6.7)
Requirement already satisfied: protobuf>=3.6.1 in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (3.11.2)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tensorflow-datasets) (3.0.4)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tensorflow-datasets) (1.24.2)
Requirement already satisfied: idna<2.9,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tensorflow-datasets) (2.8)
Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tensorflow-datasets) (2019.11.28)
Requirement already satisfied: googleapis-common-protos in /opt/conda/lib/python3.7/site-packages (from tensorflow-metadata->tensorflow-datasets) (1.6.0)
Requirement already satisfied: setuptools in /opt/conda/lib/python3.7/site-packages (from protobuf>=3.6.1->tensorflow-datasets) (41.4.0)
Note: you may need to restart the kernel to use updated packages.
Collecting tfds-nightly
  Downloading https://files.pythonhosted.org/packages/c0/08/195d77dd6caefcfa213eaf12cec8706448016f80302172d2cf34000bf7a2/tfds_nightly-4.2.0.dev202102210106-py3-none-any.whl (3.8MB)
     |████████████████████████████████| 3.8MB 5.4MB/s eta 0:00:01
Requirement already satisfied: dill in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.3.1.1)
Collecting typing-extensions; python_version < "3.8"
  Downloading https://files.pythonhosted.org/packages/60/7a/e881b5abb54db0e6e671ab088d079c57ce54e8a01a3ca443f561ccadb37e/typing_extensions-3.7.4.3-py3-none-any.whl
Collecting importlib-resources; python_version < "3.9"
  Downloading https://files.pythonhosted.org/packages/82/70/7bf5f275a738629a7252c30c8461502d3658a75363db9f4f88ddbeb9eeac/importlib_resources-5.1.0-py3-none-any.whl
Requirement already satisfied: tensorflow-metadata in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.14.0)
Requirement already satisfied: absl-py in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.8.1)
Requirement already satisfied: attrs>=18.1.0 in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (19.3.0)
Requirement already satisfied: tqdm in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (4.36.1)
Requirement already satisfied: termcolor in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.1.0)
Requirement already satisfied: six in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.12.0)
Requirement already satisfied: requests>=2.19.0 in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (2.22.0)
Requirement already satisfied: promise in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (2.2.1)
Requirement already satisfied: future in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.18.2)
Requirement already satisfied: numpy in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.17.4)
Collecting protobuf>=3.12.2
  Downloading https://files.pythonhosted.org/packages/f4/64/fd1b8f490a087eb88e1b834a8e7d45ff8e46a88eee94f86cb6f466e3767c/protobuf-3.15.1-cp37-cp37m-manylinux1_x86_64.whl (1.0MB)
     |████████████████████████████████| 1.0MB 32.1MB/s eta 0:00:01
Requirement already satisfied: zipp>=0.4; python_version < "3.8" in /opt/conda/lib/python3.7/site-packages (from importlib-resources; python_version < "3.9"->tfds-nightly) (0.6.0)
Requirement already satisfied: googleapis-common-protos in /opt/conda/lib/python3.7/site-packages (from tensorflow-metadata->tfds-nightly) (1.6.0)
Requirement already satisfied: idna<2.9,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (2.8)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (3.0.4)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (1.24.2)
Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (2019.11.28)
Requirement already satisfied: more-itertools in /opt/conda/lib/python3.7/site-packages (from zipp>=0.4; python_version < "3.8"->importlib-resources; python_version < "3.9"->tfds-nightly) (8.0.2)
Installing collected packages: typing-extensions, importlib-resources, protobuf, tfds-nightly
  WARNING: The script tfds is installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed importlib-resources-5.1.0 protobuf-3.15.1 tfds-nightly-4.2.0.dev202102210106 typing-extensions-3.7.4.3
Note: you may need to restart the kernel to use updated packages.
Collecting tensorflow
  Downloading https://files.pythonhosted.org/packages/70/dc/e8c5e7983866fa4ef3fd619faa35f660b95b01a2ab62b3884f038ccab542/tensorflow-2.4.1-cp37-cp37m-manylinux2010_x86_64.whl (394.3MB)
     |████████████████████████████████| 394.3MB 29kB/s s eta 0:00:01    |██████▌                         | 79.6MB 31.7MB/s eta 0:00:10     |█████████████████               | 210.1MB 34.0MB/s eta 0:00:06
Collecting absl-py~=0.10
  Downloading https://files.pythonhosted.org/packages/bc/58/0aa6fb779dc69cfc811df3398fcbeaeefbf18561b6e36b185df0782781cc/absl_py-0.11.0-py3-none-any.whl (127kB)
     |████████████████████████████████| 133kB 39.5MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: protobuf>=3.9.2 in /root/.local/lib/python3.7/site-packages (from tensorflow) (3.15.1)
Collecting wrapt~=1.12.1
  Downloading https://files.pythonhosted.org/packages/82/f7/e43cefbe88c5fd371f4cf0cf5eb3feccd07515af9fd6cf7dbf1d1793a797/wrapt-1.12.1.tar.gz
Collecting opt-einsum~=3.3.0
  Downloading https://files.pythonhosted.org/packages/bc/19/404708a7e54ad2798907210462fd950c3442ea51acc8790f3da48d2bee8b/opt_einsum-3.3.0-py3-none-any.whl (65kB)
     |████████████████████████████████| 71kB 9.2MB/s  eta 0:00:01
Collecting tensorflow-estimator<2.5.0,>=2.4.0
  Downloading https://files.pythonhosted.org/packages/74/7e/622d9849abf3afb81e482ffc170758742e392ee129ce1540611199a59237/tensorflow_estimator-2.4.0-py2.py3-none-any.whl (462kB)
     |████████████████████████████████| 471kB 31.4MB/s eta 0:00:01
Collecting google-pasta~=0.2
  Downloading https://files.pythonhosted.org/packages/a3/de/c648ef6835192e6e2cc03f40b19eeda4382c49b5bafb43d88b931c4c74ac/google_pasta-0.2.0-py3-none-any.whl (57kB)
     |████████████████████████████████| 61kB 10.1MB/s eta 0:00:01
Collecting grpcio~=1.32.0
  Downloading https://files.pythonhosted.org/packages/06/54/1c8be62beafe7fb1548d2968e518ca040556b46b0275399d4f3186c56d79/grpcio-1.32.0-cp37-cp37m-manylinux2014_x86_64.whl (3.8MB)
     |████████████████████████████████| 3.8MB 22.2MB/s eta 0:00:01
Collecting tensorboard~=2.4
  Downloading https://files.pythonhosted.org/packages/64/21/eebd23060763fedeefb78bc2b286e00fa1d8abda6f70efa2ee08c28af0d4/tensorboard-2.4.1-py3-none-any.whl (10.6MB)
     |████████████████████████████████| 10.6MB 23.3MB/s eta 0:00:01
Collecting six~=1.15.0
  Downloading https://files.pythonhosted.org/packages/ee/ff/48bde5c0f013094d729fe4b0316ba2a24774b3ff1c52d924a8a4cb04078a/six-1.15.0-py2.py3-none-any.whl
Collecting numpy~=1.19.2
  Downloading https://files.pythonhosted.org/packages/08/d6/a6aaa29fea945bc6c61d11f6e0697b325ff7446de5ffd62c2fa02f627048/numpy-1.19.5-cp37-cp37m-manylinux2010_x86_64.whl (14.8MB)
     |████████████████████████████████| 14.8MB 23.0MB/s eta 0:00:01
Collecting h5py~=2.10.0
  Downloading https://files.pythonhosted.org/packages/3f/c0/abde58b837e066bca19a3f7332d9d0493521d7dd6b48248451a9e3fe2214/h5py-2.10.0-cp37-cp37m-manylinux1_x86_64.whl (2.9MB)
     |████████████████████████████████| 2.9MB 34.9MB/s eta 0:00:01
Collecting astunparse~=1.6.3
  Downloading https://files.pythonhosted.org/packages/2b/03/13dde6512ad7b4557eb792fbcf0c653af6076b81e5941d36ec61f7ce6028/astunparse-1.6.3-py2.py3-none-any.whl
Collecting flatbuffers~=1.12.0
  Downloading https://files.pythonhosted.org/packages/eb/26/712e578c5f14e26ae3314c39a1bdc4eb2ec2f4ddc89b708cf8e0a0d20423/flatbuffers-1.12-py2.py3-none-any.whl
Collecting keras-preprocessing~=1.1.2
  Downloading https://files.pythonhosted.org/packages/79/4c/7c3275a01e12ef9368a892926ab932b33bb13d55794881e3573482b378a7/Keras_Preprocessing-1.1.2-py2.py3-none-any.whl (42kB)
     |████████████████████████████████| 51kB 9.4MB/s  eta 0:00:01
Requirement already satisfied, skipping upgrade: termcolor~=1.1.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (1.1.0)
Requirement already satisfied, skipping upgrade: typing-extensions~=3.7.4 in /root/.local/lib/python3.7/site-packages (from tensorflow) (3.7.4.3)
Collecting wheel~=0.35
  Downloading https://files.pythonhosted.org/packages/65/63/39d04c74222770ed1589c0eaba06c05891801219272420b40311cd60c880/wheel-0.36.2-py2.py3-none-any.whl
Collecting gast==0.3.3
  Downloading https://files.pythonhosted.org/packages/d6/84/759f5dd23fec8ba71952d97bcc7e2c9d7d63bdc582421f3cd4be845f0c98/gast-0.3.3-py2.py3-none-any.whl
Requirement already satisfied, skipping upgrade: werkzeug>=0.11.15 in /opt/conda/lib/python3.7/site-packages (from tensorboard~=2.4->tensorflow) (0.16.0)
Collecting tensorboard-plugin-wit>=1.6.0
  Downloading https://files.pythonhosted.org/packages/1a/c1/499e600ba0c618b451cd9c425ae1c177249940a2086316552fee7d86c954/tensorboard_plugin_wit-1.8.0-py3-none-any.whl (781kB)
     |████████████████████████████████| 788kB 39.0MB/s eta 0:00:01
Collecting google-auth-oauthlib<0.5,>=0.4.1
  Downloading https://files.pythonhosted.org/packages/81/67/e2c34bb0628984c7ce71cce6ba6964cb29c418873847fc285f826e032e6e/google_auth_oauthlib-0.4.2-py2.py3-none-any.whl
Collecting google-auth<2,>=1.6.3
  Downloading https://files.pythonhosted.org/packages/bf/6b/a364a4ad2a9d25904a19f53b9474ae9666b96e0653a6ca38492baf1bcf05/google_auth-1.27.0-py2.py3-none-any.whl (135kB)
     |████████████████████████████████| 143kB 26.2MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: requests<3,>=2.21.0 in /opt/conda/lib/python3.7/site-packages (from tensorboard~=2.4->tensorflow) (2.22.0)
Requirement already satisfied, skipping upgrade: markdown>=2.6.8 in /opt/conda/lib/python3.7/site-packages (from tensorboard~=2.4->tensorflow) (3.1.1)
Requirement already satisfied, skipping upgrade: setuptools>=41.0.0 in /opt/conda/lib/python3.7/site-packages (from tensorboard~=2.4->tensorflow) (41.4.0)
Collecting requests-oauthlib>=0.7.0
  Downloading https://files.pythonhosted.org/packages/a3/12/b92740d845ab62ea4edf04d2f4164d82532b5a0b03836d4d4e71c6f3d379/requests_oauthlib-1.3.0-py2.py3-none-any.whl
Collecting cachetools<5.0,>=2.0.0
  Downloading https://files.pythonhosted.org/packages/bb/72/8df2e0dc991f1a1d2c6869404e7622e8ee50d80bff357dbb57c3df70305b/cachetools-4.2.1-py3-none-any.whl
Collecting rsa<5,>=3.1.4; python_version >= "3.6"
  Downloading https://files.pythonhosted.org/packages/a0/c6/f6f92e055213860a39c98e51a10a51af473bc799a889fe8edac11108245b/rsa-4.7.1-py3-none-any.whl
Collecting pyasn1-modules>=0.2.1
  Downloading https://files.pythonhosted.org/packages/95/de/214830a981892a3e286c3794f41ae67a4495df1108c3da8a9f62159b9a9d/pyasn1_modules-0.2.8-py2.py3-none-any.whl (155kB)
     |████████████████████████████████| 163kB 31.2MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard~=2.4->tensorflow) (2019.11.28)
Requirement already satisfied, skipping upgrade: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard~=2.4->tensorflow) (1.24.2)
Requirement already satisfied, skipping upgrade: idna<2.9,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard~=2.4->tensorflow) (2.8)
Requirement already satisfied, skipping upgrade: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard~=2.4->tensorflow) (3.0.4)
Collecting oauthlib>=3.0.0
  Downloading https://files.pythonhosted.org/packages/05/57/ce2e7a8fa7c0afb54a0581b14a65b56e62b5759dbc98e80627142b8a3704/oauthlib-3.1.0-py2.py3-none-any.whl (147kB)
     |████████████████████████████████| 153kB 45.5MB/s eta 0:00:01
Collecting pyasn1>=0.1.3
  Downloading https://files.pythonhosted.org/packages/62/1e/a94a8d635fa3ce4cfc7f506003548d0a2447ae76fd5ca53932970fe3053f/pyasn1-0.4.8-py2.py3-none-any.whl (77kB)
     |████████████████████████████████| 81kB 10.2MB/s eta 0:00:01
Building wheels for collected packages: wrapt
  Building wheel for wrapt (setup.py) ... done
  Created wheel for wrapt: filename=wrapt-1.12.1-cp37-cp37m-linux_x86_64.whl size=70985 sha256=5f419a734f47aaa9886a8c087afc87001f25d2404a51d51e70405090bddb8688
  Stored in directory: /root/.cache/pip/wheels/b1/c2/ed/d62208260edbd3fa7156545c00ef966f45f2063d0a84f8208a
Successfully built wrapt
Installing collected packages: six, absl-py, wrapt, numpy, opt-einsum, tensorflow-estimator, google-pasta, grpcio, wheel, tensorboard-plugin-wit, cachetools, pyasn1, rsa, pyasn1-modules, google-auth, oauthlib, requests-oauthlib, google-auth-oauthlib, tensorboard, h5py, astunparse, flatbuffers, keras-preprocessing, gast, tensorflow
  WARNING: The scripts f2py, f2py3 and f2py3.7 are installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The script wheel is installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The scripts pyrsa-decrypt, pyrsa-encrypt, pyrsa-keygen, pyrsa-priv2pub, pyrsa-sign and pyrsa-verify are installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The script google-oauthlib-tool is installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The script tensorboard is installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The scripts estimator_ckpt_converter, import_pb_to_tensorboard, saved_model_cli, tensorboard, tf_upgrade_v2, tflite_convert, toco and toco_from_protos are installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed absl-py-0.11.0 astunparse-1.6.3 cachetools-4.2.1 flatbuffers-1.12 gast-0.3.3 google-auth-1.27.0 google-auth-oauthlib-0.4.2 google-pasta-0.2.0 grpcio-1.32.0 h5py-2.10.0 keras-preprocessing-1.1.2 numpy-1.19.5 oauthlib-3.1.0 opt-einsum-3.3.0 pyasn1-0.4.8 pyasn1-modules-0.2.8 requests-oauthlib-1.3.0 rsa-4.7.1 six-1.15.0 tensorboard-2.4.1 tensorboard-plugin-wit-1.8.0 tensorflow-2.4.1 tensorflow-estimator-2.4.0 wheel-0.36.2 wrapt-1.12.1
In [1]:
# Import TensorFlow 
import tensorflow as tf
import tensorflow_datasets as tfds
tfds.disable_progress_bar()
import tensorflow_hub as hub
In [2]:
# TODO: Make all other necessary imports.
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
%config InlineBackend.figure_format = 'retina'

import time
import numpy as np
import matplotlib.pyplot as plt

import logging
logger = tf.get_logger()
logger.setLevel(logging.ERROR)

print('Using:')
print('\t\u2022 TensorFlow version:', tf.__version__)
print('\t\u2022 tf.keras version:', tf.keras.__version__)
print('\t\u2022 Running on GPU' if tf.test.is_gpu_available() else '\t\u2022 GPU device not found. Running on CPU')
Using:
	• TensorFlow version: 2.4.1
	• tf.keras version: 2.4.0
	• GPU device not found. Running on CPU

Load the Dataset

Here you'll use tensorflow_datasets to load the Oxford Flowers 102 dataset. This dataset has 3 splits: 'train', 'test', and 'validation'. You'll also need to make sure the training data is normalized and resized to 224x224 pixels as required by the pre-trained networks.

The validation and testing sets are used to measure the model's performance on data it hasn't seen yet, but you'll still need to normalize and resize the images to the appropriate size.

In [3]:
# Download data to default local directory "~/tensorflow_datasets"
!python -m tensorflow_datasets.scripts.download_and_prepare --register_checksums=True --datasets=oxford_flowers102

# TODO: Load the dataset with TensorFlow Datasets. Hint: use tfds.load()
dataset, dataset_info = tfds.load('oxford_flowers102', with_info = True, as_supervised = True)
# TODO: Create a training set, a validation set and a test set.
training_set, testing_set, validation_set = dataset['train'], dataset['test'], dataset['validation']
2021-02-21 17:45:27.239924: W tensorflow/stream_executor/platform/default/dso_loader.cc:60] Could not load dynamic library 'libcudart.so.11.0'; dlerror: libcudart.so.11.0: cannot open shared object file: No such file or directory
2021-02-21 17:45:27.239976: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
usage: download_and_prepare.py build [-h] [--helpfull]
                                     [--module_import MODULE_IMPORT]
                                     [--builder_config_id BUILDER_CONFIG_ID]
                                     [--datasets DATASETS_KEYWORD [DATASETS_KEYWORD ...]]
                                     [--overwrite]
                                     [--max_examples_per_split [MAX_EXAMPLES_PER_SPLIT]]
                                     [--data_dir DATA_DIR]
                                     [--download_dir DOWNLOAD_DIR]
                                     [--extract_dir EXTRACT_DIR]
                                     [--manual_dir MANUAL_DIR]
                                     [--add_name_to_manual_dir]
                                     [--config CONFIG]
                                     [--config_idx CONFIG_IDX]
                                     [--imports IMPORTS]
                                     [--register_checksums]
                                     [--force_checksums_validation]
                                     [--beam_pipeline_options BEAM_PIPELINE_OPTIONS]
                                     [--exclude_datasets EXCLUDE_DATASETS]
                                     [--experimental_latest_version]
                                     [datasets [datasets ...]]
download_and_prepare.py build: error: argument --register_checksums: ignored explicit argument 'True'
Downloading and preparing dataset 328.90 MiB (download: 328.90 MiB, generated: 331.34 MiB, total: 660.25 MiB) to /root/tensorflow_datasets/oxford_flowers102/2.1.1...
Dataset oxford_flowers102 downloaded and prepared to /root/tensorflow_datasets/oxford_flowers102/2.1.1. Subsequent calls will reuse this data.

Explore the Dataset

In [4]:
dataset_info
# TODO: Get the number of examples in each set from the dataset info.
print("Total number of examples:")
total_num_examples_train = dataset_info.splits['train'].num_examples
print('\u2022 Train: {:,} images'.format(total_num_examples_train))

total_num_examples_test = dataset_info.splits['test'].num_examples
print('\u2022 Test: {:,} images'.format(total_num_examples_test))

total_num_examples_val = dataset_info.splits['validation'].num_examples
print('\u2022 Validation: {:,} images'.format(total_num_examples_val))

# TODO: Get the number of classes in the dataset from the dataset info.
num_classes = dataset_info.features['label'].num_classes
print('The Dataset has a total of:')
print('\u2022 {:,} classes'.format(num_classes))

print(f"Labels: {dataset_info.features['label']}")
Total number of examples:
• Train: 1,020 images
• Test: 6,149 images
• Validation: 1,020 images
The Dataset has a total of:
• 102 classes
Labels: ClassLabel(shape=(), dtype=tf.int64, num_classes=102)
In [5]:
# TODO: Print the shape and corresponding label of 3 images in the training set.
for image, label in training_set.take(3):
    i_label = label.numpy()
    print(f"Label = {i_label} ({dataset_info.features['label'].names[i_label]}) shape: {image.numpy().shape}")
Label = 72 (water lily) shape: (500, 667, 3)
Label = 84 (desert-rose) shape: (500, 666, 3)
Label = 70 (gazania) shape: (670, 500, 3)
In [6]:
# TODO: Plot 1 image from the training set. 
dataset_info.features['label'].names
for image, label in training_set.take(1):
    image = image.numpy()
    label = label.numpy()

plt.imshow(image)

# Set the title of the plot to the corresponding image label. 
plt.title(dataset_info.features['label'].names[label])
plt.show()

Label Mapping

You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.

In [7]:
import json
with open('label_map.json', 'r') as f:
    class_names = json.load(f)
In [8]:
# TODO: Plot 1 image from the training set. Set the title 
# of the plot to the corresponding class name. 
for image, label in training_set.take(1):
    image = image.numpy()
    label = label.numpy()

plt.imshow(image)
plt.title(class_names[str(label+1)])
plt.show()

print(f"The label of this image is: {label}")
print(f"The class name of this image is: {class_names[str(label+1)]}")
The label of this image is: 72
The class name of this image is: water lily

Create Pipeline

In [9]:
# TODO: Create a pipeline for each set.
batch_size = 32
image_size = 224

def format_image(image, label):
    image = tf.cast(image, tf.float32)
    image = tf.image.resize(image, (image_size, image_size))
    image /= 255
    return image, label


training_batches = training_set.shuffle(total_num_examples_train//4).map(format_image).batch(batch_size).prefetch(1)
validation_batches = validation_set.map(format_image).batch(batch_size).prefetch(1)
testing_batches = testing_set.map(format_image).batch(batch_size).prefetch(1)

Build and Train the Classifier

Now that the data is ready, it's time to build and train the classifier. You should use the MobileNet pre-trained model from TensorFlow Hub to get the image features. Build and train a new feed-forward classifier using those features.

We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students!

Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:

  • Load the MobileNet pre-trained network from TensorFlow Hub.
  • Define a new, untrained feed-forward network as a classifier.
  • Train the classifier.
  • Plot the loss and accuracy values achieved during training for the training and validation set.
  • Save your trained model as a Keras model.

We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!

When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right.

Note for Workspace users: One important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. Also, If your model is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh), you should reduce the size of your hidden layers and train again.

In [10]:
# TODO: Build and train your network.
URL = "https://tfhub.dev/google/imagenet/mobilenet_v3_small_100_224/feature_vector/5"
feature_extractor = hub.KerasLayer(URL, input_shape=(image_size, image_size,3))
In [11]:
feature_extractor.trainable = False
In [12]:
model = tf.keras.Sequential([
        feature_extractor,
        tf.keras.layers.Dense(102, activation = 'softmax')
])

model.summary()
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
keras_layer (KerasLayer)     (None, 1024)              1529968   
_________________________________________________________________
dense (Dense)                (None, 102)               104550    
=================================================================
Total params: 1,634,518
Trainable params: 104,550
Non-trainable params: 1,529,968
_________________________________________________________________
In [13]:
#compile model
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
In [14]:
#check initial prediction
for image_batch, label_batch in testing_batches.take(1):
    ps = model.predict(image_batch)
    images = image_batch.numpy().squeeze()
    labels = label_batch.numpy()

plt.figure(figsize=(10,15))

for n in range(30):
    plt.subplot(6,5,n+1)
    plt.imshow(images[n], cmap = plt.cm.binary)
    color = 'green' if np.argmax(ps[n]) == labels[n] else 'red'
    plt.title(class_names[str(np.argmax(ps[n])+1)], color=color)
    plt.axis('off')
In [15]:
#training
EPOCHS = 10

history = model.fit_generator(training_batches,
                              epochs=EPOCHS,
                              validation_data=validation_batches)
Epoch 1/10
32/32 [==============================] - 22s 550ms/step - loss: 4.5145 - accuracy: 0.0639 - val_loss: 3.1758 - val_accuracy: 0.4569
Epoch 2/10
32/32 [==============================] - 17s 519ms/step - loss: 2.5493 - accuracy: 0.6899 - val_loss: 2.1310 - val_accuracy: 0.6863
Epoch 3/10
32/32 [==============================] - 17s 530ms/step - loss: 1.4326 - accuracy: 0.8909 - val_loss: 1.5813 - val_accuracy: 0.7578
Epoch 4/10
32/32 [==============================] - 17s 521ms/step - loss: 0.8747 - accuracy: 0.9479 - val_loss: 1.2921 - val_accuracy: 0.7931
Epoch 5/10
32/32 [==============================] - 17s 521ms/step - loss: 0.6144 - accuracy: 0.9700 - val_loss: 1.1239 - val_accuracy: 0.8176
Epoch 6/10
32/32 [==============================] - 17s 523ms/step - loss: 0.4175 - accuracy: 0.9902 - val_loss: 1.0139 - val_accuracy: 0.8225
Epoch 7/10
32/32 [==============================] - 17s 528ms/step - loss: 0.3221 - accuracy: 0.9891 - val_loss: 0.9392 - val_accuracy: 0.8314
Epoch 8/10
32/32 [==============================] - 17s 524ms/step - loss: 0.2600 - accuracy: 0.9946 - val_loss: 0.8820 - val_accuracy: 0.8343
Epoch 9/10
32/32 [==============================] - 16s 509ms/step - loss: 0.2034 - accuracy: 0.9962 - val_loss: 0.8386 - val_accuracy: 0.8422
Epoch 10/10
32/32 [==============================] - 17s 515ms/step - loss: 0.1658 - accuracy: 0.9986 - val_loss: 0.8044 - val_accuracy: 0.8431
In [16]:
#check prediction -- after training
for image_batch, label_batch in testing_batches.take(1):
    ps = model.predict(image_batch)
    images = image_batch.numpy().squeeze()
    labels = label_batch.numpy()

plt.figure(figsize=(10,15))

for n in range(30):
    plt.subplot(6,5,n+1)
    plt.imshow(images[n], cmap = plt.cm.binary)
    color = 'green' if np.argmax(ps[n]) == labels[n] else 'red'
    plt.title(class_names[str(np.argmax(ps[n])+1)], color=color)
    plt.axis('off')
In [17]:
# TODO: Plot the loss and accuracy values achieved during training for the training and validation set.
training_accuracy = history.history['accuracy']
validation_accuracy = history.history['val_accuracy']

training_loss = history.history['loss']
validation_loss = history.history['val_loss']

epochs_range=range(EPOCHS)

plt.figure(figsize=(8, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, training_accuracy, label='Training Accuracy')
plt.plot(epochs_range, validation_accuracy, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')

plt.subplot(1, 2, 2)
plt.plot(epochs_range, training_loss, label='Training Loss')
plt.plot(epochs_range, validation_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()

Testing your Network

It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.

In [18]:
# TODO: Print the loss and accuracy values achieved on the entire test set.
loss, accuracy = model.evaluate(testing_batches)

print('\nLoss on the TEST Set: {:,.3f}'.format(loss))
print('Accuracy on the TEST Set: {:.3%}'.format(accuracy))
193/193 [==============================] - 49s 253ms/step - loss: 0.9271 - accuracy: 0.8104

Loss on the TEST Set: 0.927
Accuracy on the TEST Set: 81.038%

Save the Model

Now that your network is trained, save the model so you can load it later for making inference. In the cell below save your model as a Keras model (i.e. save it as an HDF5 file).

In [19]:
# TODO: Save your trained model as a Keras model.
t = time.time()

saved_p2 = './my_model_{}.h5'.format(int(t))

model.save(saved_p2)

Load the Keras Model

Load the Keras model you saved above.

In [20]:
# TODO: Load the Keras model
reloaded_keras_model = tf.keras.models.load_model(saved_p2,custom_objects={'KerasLayer': hub.KerasLayer})

reloaded_keras_model.summary()
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
keras_layer (KerasLayer)     (None, 1024)              1529968   
_________________________________________________________________
dense (Dense)                (None, 102)               104550    
=================================================================
Total params: 1,634,518
Trainable params: 104,550
Non-trainable params: 1,529,968
_________________________________________________________________

Inference for Classification

Now you'll write a function that uses your trained network for inference. Write a function called predict that takes an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

The predict function will also need to handle pre-processing the input image such that it can be used by your model. We recommend you write a separate function called process_image that performs the pre-processing. You can then call the process_image function from the predict function.

Image Pre-processing

The process_image function should take in an image (in the form of a NumPy array) and return an image in the form of a NumPy array with shape (224, 224, 3).

First, you should convert your image into a TensorFlow Tensor and then resize it to the appropriate size using tf.image.resize.

Second, the pixel values of the input images are typically encoded as integers in the range 0-255, but the model expects the pixel values to be floats in the range 0-1. Therefore, you'll also need to normalize the pixel values.

Finally, convert your image back to a NumPy array using the .numpy() method.

In [21]:
# TODO: Create the process_image function
image_size = 224

# TODO: Create the process_image function
def process_image(image):
    image = tf.cast(image, tf.float32)
    image = tf.image.resize(image, (image_size, image_size))
    image /= 255
    return image

To check your process_image function we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

The code below loads one of the above images using PIL and plots the original image alongside the image produced by your process_image function. If your process_image function works, the plotted image should be the correct size.

In [22]:
from PIL import Image

image_path = './test_images/hard-leaved_pocket_orchid.jpg'
im = Image.open(image_path)
test_image = np.asarray(im)

processed_test_image = process_image(test_image)

fig, (ax1, ax2) = plt.subplots(figsize=(10,10), ncols=2)
ax1.imshow(test_image)
ax1.set_title('Original Image')
ax2.imshow(processed_test_image)
ax2.set_title('Processed Image')
plt.tight_layout()
plt.show()

Once you can get images in the correct format, it's time to write the predict function for making inference with your model.

Inference

Remember, the predict function should take an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

Note: The image returned by the process_image function is a NumPy array with shape (224, 224, 3) but the model expects the input images to be of shape (1, 224, 224, 3). This extra dimension represents the batch size. We suggest you use the np.expand_dims() function to add the extra dimension.

In [23]:
test_image = './test_images/hard-leaved_pocket_orchid.jpg'

def where(needles,haystack):
    classes = []
    for i in needles:
        found = np.where(i == haystack)
        classes.append(str(found[0][0]+1))
    
    return classes
        
# TODO: Create the predict function
def predict(image_path,model,top_k):
    #process image
    im = Image.open(image_path)
    image = np.asarray(im)
    
    processed_image = process_image(image)
    #print(f"Shape before: {processed_image.shape}")
    processed_image = np.expand_dims(processed_image,axis=0)
    #print(f"Shape after: {processed_image.shape}")
    ps = model.predict(processed_image)

    predictions = ps[0]
    #top_k probalities
    probs = np.sort(predictions)[::-1][:top_k]

    #top_k classes index
    classes = where(probs,predictions)
        
    return probs,classes

probs, classes = predict(test_image,reloaded_keras_model,5)
print(probs)
print(classes)
[0.97656566 0.0040137  0.0024339  0.00203312 0.00152733]
['2', '7', '80', '102', '13']

Sanity Check

It's always good to check the predictions made by your model to make sure they are correct. To check your predictions we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

In the cell below use matplotlib to plot the input image alongside the probabilities for the top 5 classes predicted by your model. Plot the probabilities as a bar graph. The plot should look like this:

You can convert from the class integer labels to actual flower names using class_names.

In [24]:
# TODO: Plot the input image along with the top 5 classes
#image_path = './test_images/hard-leaved_pocket_orchid.jpg'
#image_path = './test_images/cautleya_spicata.jpg'
#image_path = './test_images/orange_dahlia.jpg'
image_path = './test_images/wild_pansy.jpg'

im = Image.open(image_path)
image = np.asarray(im)

#the prediction
probs, classes = predict(image_path,reloaded_keras_model,5)

#plot
fig, (ax1, ax2) = plt.subplots(figsize=(6,9), ncols=2)
ax1.imshow(image, cmap = plt.cm.binary)
ax1.axis('off')
#ax1.set_title(class_names[classes[0]]) #top class
ax2.barh(np.arange(5), probs)
ax2.set_aspect(0.1)
ax2.set_yticks(np.arange(5))

classes_matched = [class_names[i] for i in classes]
#print(classes_matched)
y_pos = np.arange(len(classes_matched))
ax2.set_yticks(y_pos)
ax2.set_yticklabels(classes_matched, size='small');
ax2.set_title('Class Probability')
ax2.set_xlim(0, 1.1)
plt.tight_layout()
In [ ]: